import http.client
import time
import os

import adbutils.errors
import uiautomator2 as u2
import urllib3.exceptions

import settings
from concurrent.futures.thread import ThreadPoolExecutor
import requests
import random
import json
from src.devices import DevicesDriver
import queue

import asyncio
import websockets

def error_handle(func):
    def wrapper(self, *args, **kwargs):
        try:
            result = func(self, *args, **kwargs)
            self.status = "正常"
        except RuntimeError as e:
            self.send_message(self.port)
        except http.client.RemoteDisconnected as e:
            self.send_message(self.port)
        except urllib3.exceptions.ProtocolError as e:
            self.send_message(self.port)
        except requests.exceptions.ConnectionError as e:
            self.send_message(self.port)
        except adbutils.errors.AdbError as e:
            self.send_message(self.port)

        return result

    return wrapper


class Driver():

    def __init__(self, device_obj):
        self.device_obj = device_obj
        self.device: u2.connect = device_obj["device"]

        self.device.unlock()
        self.device.healthcheck
        self.port = device_obj['port']
        # self.device.debug = True
        self.device.implicitly_wait(5.0)  # 查找元素的默认等待时长
        self.first_gift_name = None
        self.gift_swipe_range = None
        self.first_gift_location = []
        self.width = self.device_obj['display']['width']
        self.height = self.device_obj['display']['height']
        self.douyin_name = None
        self.status = "正常"
        self.stop = False
        # 创建观察器
        # self.watcher = self.driver.watcher(name="chen")

    def send_message(self, message):
        """创建一个临时的WebSocket客户端并发送消息，发送完就关闭"""
        self.status = "连接断开"
        async def client_thread():
            async with websockets.connect('ws://localhost:7788') as websocket:
                await websocket.send(message)
                # print(f'{message} 设备断开了， 抖音名是: {self.douyin_name}')

        asyncio.run(client_thread())

    # def error_handle(self, func):
    #     def wrapper(self, *args, **kwargs):
    #         try:
    #             result = func(self, *args, **kwargs)
    #         except RuntimeError as e:
    #             self.send_message(self.port)
    #         except http.client.RemoteDisconnected as e:
    #             self.send_message(self.port)
    #         except urllib3.exceptions.ProtocolError as e:
    #             self.send_message(self.port)
    #         except requests.exceptions.ConnectionError as e:
    #             self.send_message(self.port)
    #         except adbutils.errors.AdbError as e:
    #             self.send_message(self.port)
    #
    #         return result
    #
    #     return wrapper


    def exce_shell(self, command):
        """
        发送 adb 命令
        :param command:
        :return:
        """
        print("prot->", self.port)
        print("com-->", command)
        url = f'http://127.0.0.1:{self.port}/shell'
        data = {
            'command': command,
            'timeout': '60'
        }

        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.post(url, data=json.dumps(data), headers=headers)
        print(response.text)
        # 检查响应状态码
        if response.status_code == 200:
            return True
        return False

    @error_handle
    def get_douyin_name(self):
        """获取抖音名字"""
        if self.douyin_name:
            print("抖音名字已经存在了")
            return {"name": self.douyin_name, "device": self.port}
        me_btn = self.device(**settings.me)
        count = 0
        while count < 3:
            if not me_btn.exists():
                time.sleep(5)
                count += 1

            me_btn.click()
            douyin_name = self.device.xpath(settings.douyin_name)
            if not douyin_name.exists:
                time.sleep(2)
            name = douyin_name.text
            if name:
                self.douyin_name = name
                self.send_message(self.douyin_name)
                self.device(**settings.index_page).click()
                return {"name": name, "device": self.port}

        return {"name": "", "device": self.port}


    @error_handle
    def app_start(self):
        self.device.app_start(settings.app_name, settings.activity_name)
        # 查看是否出现广告页面
        is_skip = self.device(**settings.skip)
        if is_skip.exists():
            is_skip.click()
        return self.get_douyin_name()

    @error_handle
    def app_stop(self):
        # res = self.exce_shell(settings.stop_app)
        # if res:
        #     print(f"【{self.port}】 程序关闭成功")
        # else:
        #     print(f"【{self.port}】 程序关闭失败")
        self.device.app_stop(settings.app_name)

    @error_handle
    def find_element_count(self, **kwargs):
        """根据 resourceId_str 获取元素的个数"""
        url = f'http://127.0.0.1:{self.port}/jsonrpc/0'
        headers = {'Content-Type': 'application/json'}

        payload = {
            'jsonrpc': '2.0',
            'id': '1d4cc6c68c74b5454bb62c9e75617c32',
            'method': 'waitForExists',
            'params': [
                {
                    'mask': 18874368,
                    'childOrSibling': [],
                    'childOrSiblingSelector': [],
                    'instance': 0
                },
                5000
            ]
        }
        self.device._json_call()
        if len(kwargs) > 0:
            for key, val in kwargs.items():
                payload['params'][0][key] = val
        response = requests.post(url, json=payload, headers=headers)
        data = response.json()  # {"jsonrpc":"2.0","id":"b8b72743f90bc5090926b68200046c59","result":1} 返回元素的个数
        return data['result']

    @error_handle
    def element_exist(self, **kwargs):
        """根据 resourceId_str 判断元素是否存在"""
        url = f'http://127.0.0.1:{self.port}/jsonrpc/0'
        headers = {'Content-Type': 'application/json'}

        payload = {
            'jsonrpc': '2.0',
            'id': '1d4cc6c68c74b5454bb62c9e75617c32',
            'method': 'waitForExists',
            'params': [
                {
                    'mask': 18874368,
                    'childOrSibling': [],
                    'childOrSiblingSelector': [],
                    # "resourceId": resourceId_str,
                    'instance': 0
                },
                5000
            ]
        }
        if len(kwargs) > 0:
            for key, val in kwargs.items():
                payload['params'][0][key] = val

        response = requests.post(url, data=json.dumps(payload), headers=headers)
        data = response.json()  # {"jsonrpc":"2.0","id":"1d4cc6c68c74b5454bb62c9e75617c32","result":true}
        return data['result']

    @error_handle
    def get_element_text(self, **kwargs):
        """根据 resourceId_str 获取元素的文本信息"""
        url = f'http://127.0.0.1:{self.port}/jsonrpc/0'
        headers = {'Content-Type': 'application/json'}

        payload = {
            'jsonrpc': '2.0',
            'id': '466467e0cb9b097785aed09a611fe86e',
            'method': 'getText',
            'params': [
                {
                    'mask': 18874368,
                    'childOrSibling': [],
                    'childOrSiblingSelector': [],
                    'instance': 0
                }
            ]
        }
        if len(kwargs) > 0:
            for key, val in kwargs.items():
                payload['params'][0][key] = val

        response = requests.post(url, data=json.dumps(payload), headers=headers)
        data = response.json()  # {"jsonrpc":"2.0","id":"466467e0cb9b097785aed09a611fe86e","result":"@博洛尼整体家装官方号"}
        return data.get('result')

    @error_handle
    def swipe(self, start_x, start_y, end_x, end_y, duration=30):
        """根据起始坐标和终点坐标进行滑动， 间隔为 duration """
        url = f'http://127.0.0.1:{self.port}/jsonrpc/0'
        headers = {'Content-Type': 'application/json'}

        payload = {
            'jsonrpc': '2.0',
            'id': 'f7d8d37cdfd2f1246493976bc7c7038d',
            'method': 'swipe',
            'params': [start_x, start_y, end_x, end_y, duration]
        }

        response = requests.post(url, headers=headers, data=json.dumps(payload))
        if response.status_code != 200:
            print(f'【{self.port}】 swipe_up fail:', response.status_code)

    @error_handle
    def swipe_up(self, duration=20):
        """向上滑动"""
        # 'display': {'width': 1080, 'height': 2280},
        width = self.device_obj['display']['width']
        height = self.device_obj['display']['height']
        # 计算滑动起点和终点的坐标
        start_x = width // 2
        start_y = int(height * 0.75)
        end_y = int(height * 0.2)
        # 执行上滑操作
        self.swipe(start_x, start_y, start_x, end_y, duration)

    @error_handle
    def swipe_down(self, duration=20):
        """向上滑动"""
        # 'display': {'width': 1080, 'height': 2280},
        width = self.device_obj['display']['width']
        height = self.device_obj['display']['height']
        # 计算滑动起点和终点的坐标
        start_x = width // 2
        end_y = int(height * 0.75)
        start_y = int(height * 0.2)
        # 执行下滑操作
        self.swipe(start_x, start_y, start_x, end_y, duration)

    @error_handle
    def find_room(self, room_name, contain=True, is_up=True):
        """
        根据传入的直播间名称，去找到对应的直播间
        :param room_name: 直播间名称
        :param is_up: 屏幕滑动的方向，默认是向上滑动
        :return:
        """
        if is_up:
            swipe_func = self.swipe_up
        else:
            swipe_func = self.swipe_down
        while True:
            room_ele = self.device.xpath(settings.room_name)
            if not room_ele.exists:
                swipe_func()
                continue
            cur_name = room_ele.text
            print("cur_name-->", cur_name)
            if cur_name == "@" + room_name:
                print("找到直播间了")
                self.device(text="点击进入直播间").click()
                time.sleep(1)
                break
            if contain:
                if f"@{room_name}" in cur_name:
                    print("找到直播间了")
                    self.device(text="点击进入直播间").click()
                    time.sleep(1)
                    break
            print("没找到")
            swipe_func()
            time.sleep(0.5)

    @error_handle
    def click_care(self):
        """点击直播间的关注"""
        count = 0
        while count < 3:
            care_btn = self.device(**settings.room_care)
            if care_btn.exists():
                care_btn.click()
                print("点击完成")
                break
            count += 1
            time.sleep(0.5)

    @error_handle
    def get_element_info(self, **kwargs):
        """获取某个元素的详细信息，坐标等"""
        url = f'http://127.0.0.1:{self.port}/jsonrpc/0'
        headers = {'Content-Type': 'application/json'}

        payload = {
            'jsonrpc': '2.0',
            'id': 'a2aeb694260e77730b0880638ef071a5',
            'method': 'objInfo',
            'params': [
                {
                    'mask': 2097153,
                    'childOrSibling': [],
                    'childOrSiblingSelector': []
                }
            ]
        }

        if len(kwargs) > 0:
            for key, val in kwargs.items():
                payload['params'][0][key] = val

        response = requests.post(url, data=json.dumps(payload), headers=headers)
        data = response.json()
        print("data->", data)
        if data.get("error"):
            return None
        return data.get("result")

    def get_element_Coordinates(self, element_info):
        """根据元素的具体信息，获取到该元素的中心坐标，用于点击事件"""
        bounds = element_info.get("bounds")
        if bounds is None:
            print("元素没有宽高属性")
            return None

        bottom = bounds.get("bottom")
        left = bounds.get("left")
        right = bounds.get("right")
        top = bounds.get("top")
        x = (int(left) + int(right)) / 2
        y = (int(bottom) + int(top)) / 2
        return float(x), float(y)

    def click_element(self, x, y):
        """根据坐标点击某个元素"""
        url = f'http://127.0.0.1:{self.port}/jsonrpc/0'
        headers = {'Content-Type': 'application/json'}

        payload = {
            'jsonrpc': '2.0',
            'id': '40ddb611d387e4d3b9674f58c726558d',
            'method': 'click',
            'params': [x, y]
        }

        response = requests.post(url, data=json.dumps(payload), headers=headers)
        data = response.json()
        return data.get("result")

    def click(self, double=False, **kwargs):
        element_info = self.get_element_info(**kwargs)
        if element_info is None:
            print(f"【{self.port}】该元素不存在")
            return
        is_exist = self.get_element_Coordinates(element_info)
        if is_exist:
            print("x, y", is_exist)
            x, y = is_exist
            x = round(x, 1)
            y = round(y, 1)
            success = self.click_element(x, y)
            if success:
                if double:
                    self.click_element(x, y)
                print(f"【{self.port}】 点击成功")
            return success

    # def get_first_gift_size(self):
    #     """获取第一个礼物的尺寸，用于后面计算滑动的距离"""
    #     # 第一个礼物的定位
    #     className_str = "android.widget.Button"
    #     url = f'http://127.0.0.1:{self.port}/jsonrpc/0'
    #     headers = {'Content-Type': 'application/json'}
    #
    #     payload = {
    #         'jsonrpc': '2.0',
    #         'id': '43596e18eda38e3add1269ced6222f6f',
    #         'method': 'objInfo',
    #         'params': [
    #             {
    #                 'mask': 16777232,
    #                 'childOrSibling': [],
    #                 'childOrSiblingSelector': [],
    #                 'className': className_str,
    #                 'instance': 5
    #             },
    #         ]
    #     }
    #     try:
    #         response = requests.post(url, data=json.dumps(payload), headers=headers)
    #         data = response.json()
    #         if data.get("result"):
    #             return data["result"]
    #     except Exception as e:
    #         self.get_first_gift_size()

    def get_first_gift_name(self):
        """获取第一个礼物的尺寸，用于后面计算滑动的距离"""
        # # 第一个礼物的定位
        # className_str = "android.widget.Button"
        # url = f'http://127.0.0.1:{self.port}/jsonrpc/0'
        # headers = {'Content-Type': 'application/json'}
        #
        # payload = {
        #     'jsonrpc': '2.0',
        #     'id': '43596e18eda38e3add1269ced6222f6f',
        #     'method': 'objInfo',
        #     'params': [
        #         {
        #             'mask': 16777232,
        #             'childOrSibling': [],
        #             'childOrSiblingSelector': [],
        #             'className': className_str,
        #             'instance': 5
        #         },
        #     ]
        # }
        #
        # response = requests.post(url, data=json.dumps(payload), headers=headers)
        # data = response.json()
        first_gift_name = ""
        try:
            first_gift_ele = self.device(resourceId="com.ss.android.ugc.aweme:id/recycler_view").child()[0]
            info = first_gift_ele.info
            contentDescription = info.get("contentDescription")
            if contentDescription:
                first_gift_name = contentDescription.split(" ")[0]
                self.first_gift_name = first_gift_name
            bounds = info.get("bounds")
            if bounds:
                bottom = bounds.get("bottom")
                left = bounds.get("left")
                right = bounds.get("right")
                top = bounds.get("top")
                self.first_gift_location = [(left + right) / 2, (bottom + top) / 2]
        except Exception as e:
            print(e)
        finally:
            return first_gift_name

    def get_gift_window_swipe(self):
        """
        获取礼物区域滑动的起点和终点
        :return:
        """
        gift_window = self.device.xpath(settings.gift_ele["gift_window"])
        if not gift_window.exists:
            print("[get_gift_window_swipe]礼物元素没找到，请确认礼物弹窗已打开")
            return
        gift_window_info = gift_window.info
        bounds = gift_window_info.get("bounds")
        if not bounds:
            print("[get_gift_window_swipe]礼物元素没找到，请确认礼物弹窗已打开")
            return
        bottom = bounds.get("bottom")
        left = bounds.get("left")
        right = bounds.get("right")
        top = bounds.get("top")
        x = (left + right) / 2
        start_y = bottom - ((bottom - top) / 6)
        # end_y = bottom - ((bottom - top) / 6 * 5)
        end_y = bottom - ((bottom - top) - 100)
        return x, start_y, x, end_y

    def open_gift_window(self):
        """开打送礼物的窗口"""
        gift_window = self.device(**settings.gift_ele['gift_logo'])
        if gift_window.exists():
            print("礼物窗口已打开，不需要点击礼物按钮")
            return
        gift_btn = self.device(**settings.gift_ele['gift_icon'])
        if gift_btn.exists():
            print("礼物窗口没打开，准备打开")
            # gift_btn.click()
            x, y = gift_btn.center()
            self.device.click(x, y)
            print("点击礼物按钮")
            time.sleep(2)
            # 如果2秒后还不存在，就再等2秒
            # gift_window = self.device(**settings.gift_ele['gift_logo'])
            # if not gift_window.exists():
            #     time.sleep(2)

    def init_gift_window(self):
        """初始化礼物窗口，每次送礼物都回到第一个礼物的位置"""
        # 上一次的礼物名称
        last_gift_name = ""
        if self.gift_swipe_range:
            x1, y1, x2, y2 = self.gift_swipe_range
        else:
            x1, y1, x2, y2 = self.get_gift_window_swipe()
        while True:
            self.swipe(x2, y2, x1, y1)
            # self.device.swipe(x2, y2, x1, y1)
            # cur_gift_name = self.get_element_text(resourceId="com.ss.android.ugc.aweme:id/g81")
            cur_ele = self.device.xpath(settings.gift_ele['all_gift_btn'])

            info = cur_ele.info
            contentDescription = info.get("contentDescription")
            if contentDescription:
                cur_gift_name = contentDescription.split(" ")[0]
            print(cur_gift_name)
            print(last_gift_name)
            if cur_gift_name == last_gift_name and len(cur_gift_name) > 0:
                print("已滑动到第一个礼物")
                break
            last_gift_name = cur_gift_name
            time.sleep(0.5)

        # 找到第一个
        first_gift_name = self.get_first_gift_name()
        self.gift_swipe_range = x1, y1, x2, y2
        self.first_gift_name = first_gift_name
        # 判断第一个礼物是否能是选择状态
        give_icon = self.device.xpath(settings.gift_ele['gift_name_btn'].format(first_gift_name))
        info = give_icon.info
        contentDescription = info.get("contentDescription")
        if "双击赠送" not in contentDescription:
            # print("不是选中状态")
            give_icon.click()


    def click_gift(self, click_ele, count, giftInterval_list):
        """
        根据礼物的坐标， 已经需要送的个数，礼物的时间间隔来点击礼物，并赠送
        :param x:
        :param y:
        :param count:
        :param giftInterval_list:
        :return:
        """

        # self.device.click(x, y)
        click_ele.click()
        # 查看当前抖币是否还充足，如果不充足，就停止
        time.sleep(2)
        is_pay = self.device(text="当前抖币不足")
        if is_pay.exists():
            print("当前抖币不足，请充值后再送")
            self.device.click(self.width / 2, self.height / 5)
            return {"result": None, "err": "当前抖币已不足，请充值后再送"}
        if count == 1:
            return {"result": "ok", "err": None}
        for i in range(count - 1):
            if self.stop:
                return {"result": "已停止", "err": None}
            cur_Interval = 2
            if giftInterval_list:
                cur_Interval = float(giftInterval_list[i])

            time.sleep(cur_Interval)
            # self.device.click(x, y)
            click_ele.click()
            # 查看当前抖币是否还充足，如果不充足，就停止
            is_pay = self.device(text="当前抖币不足")
            if is_pay.exists():
                print("当前抖币不足，请充值后再送")
                self.device.click(self.width / 2, self.height / 5)
                return {"result": None, "err": "当前抖币已不足，请充值后再送"}
        return {"result": "ok", "err": None}

    def window_exist_gift(self, gift_name):
        """
        判断当前窗口是否已经存在想要找的礼物了，如果存在就不滑动寻找了
        :param gift_name:
        :return:
        """
        # 先看看当前礼物是否没有被选中，如果没有，就直接点击选中， 如果判断不出来，就遍历一遍
        gift_ele = self.device.xpath(settings.gift_ele['gift_name_btn'].format(gift_name))
        # gift_ele = self.device.xpath('//*[@resource-id="com.ss.android.ugc.aweme:id/recycler_view"]/android.widget.Button[contains(@content-desc, "小心心")]').all()
        # for i in gift_ele:
        #     print(i.info)
        if gift_ele.exists:
            print("当前礼物没有被选中，且存在当前窗口")
            info = gift_ele.info
            contentDescription = info.get("contentDescription")
            if "双击赠送" not in contentDescription:
                gift_ele.click()
            return gift_ele

        gift_list = self.device.xpath(settings.gift_ele['all_gift_btn']).all()
        # 遍历当前礼物窗口的所有礼物，看看当前窗口第一个礼物是不是想要的礼物，如果不是就选中，然后再直接找，而不是遍历找，遍历太非时间了
        for gift_ele in gift_list:
            info = gift_ele.info
            contentDescription = info.get("contentDescription")
            if not contentDescription:
                continue
            cur_gift_name = contentDescription.split(" ")[0]
            check = contentDescription.split(" ")[-1]
            if cur_gift_name != gift_name:
                if check != "双击赠送":
                    gift_ele.click()
                break

        gift_ele = self.device.xpath(settings.gift_ele['gift_name_btn'].format(gift_name))
        if gift_ele.exists:
            # print("当前礼物没有被选中，且存在当前窗口")
            # x, y = gift_ele.center()
            # self.device.click(x, y)
            # return x, y
            return gift_ele

    @error_handle
    def find_given_gift(self, gift_name, count=1, giftInterval_list=[]):
        """
        根据礼物名称来找礼物, 并调用点击方法，和点击的次数，去送礼物
        :param gift_name:
        :param count:
        :param giftInterval_list:
        :return:
        """

        self.open_gift_window()
        # 先判断一下当前页面是否存在想要的礼物，如果存在就不滑动寻找了
        cur_center = self.window_exist_gift(gift_name)
        if cur_center:
            print("当前页面存在想到的礼物，就不滑动了")
            return self.click_gift(cur_center, count, giftInterval_list)
        self.init_gift_window()

        if gift_name == self.first_gift_name:
            print("找到礼物了，且是第一个礼物")
            first_gift = self.device.xpath(settings.gift_ele['gift_name_btn'].format(gift_name))
            return self.click_gift(first_gift, count, giftInterval_list)

        # 上一次的礼物名称
        last_gift_name = ""
        x1, y1, x2, y2 = self.gift_swipe_range
        while True:
            if self.stop:
                return {"result": '已停止', "err": None}
            # 判断当前礼物是否在页面中出现
            # is_exist = self.get_element_info(resourceId="com.ss.android.ugc.aweme:id/g81", text=gift_name)
            cur_gift = self.device.xpath(settings.gift_ele['gift_name_btn'].format(gift_name))
            # elem = self.device(resourceId="com.ss.android.ugc.aweme:id/g81", text=gift_name)
            if cur_gift.exists:
                print("找到该礼物了")
                # self.click(double=True, resourceId="com.ss.android.ugc.aweme:id/g81", text=gift_name)
                # x, y = self.device(double=True, resourceId="com.ss.android.ugc.aweme:id/g81", text=gift_name).center()
                # x, y = cur_gift.center()
                # print("zuob-->", x, y)
                # self.device.click(x, y)
                cur_gift.click()
                return self.click_gift(cur_gift, count, giftInterval_list)

            # 获取当前第一个礼物的名字，判断与上次礼物名字是否一样，如果一样，表示已经滑到底部了，终止滑动
            # cur_gift_name = self.get_element_text(resourceId="com.ss.android.ugc.aweme:id/g81")
            cur_first_gift_name = self.device.xpath(settings.gift_ele['all_gift_btn'])
            info = cur_first_gift_name.info
            contentDescription = info.get("contentDescription")
            cur_gift_name = contentDescription.split(" ")[0]
            print("cur-name->", cur_gift_name)
            print("last-name-->", last_gift_name)
            if cur_gift_name == last_gift_name and cur_gift_name is not None:
                print("已经滑动到底部了，还是没有找到你想要的礼物")
                return {"result": None, "err": "没有找到想要的礼物"}
            last_gift_name = cur_gift_name
            self.swipe(x1, y1, x2, y2, 20)
            time.sleep(0.5)

    @error_handle
    def set_text(self, input_text, count=1, interval=0.5):
        """
        在直播间发评论， 可以控制评论的次数和时间间隔
        :param input_text: 要输入的内容
        :param count: 评论的次数
        :param interval: 每次评论的间隔 int
        :return:
        """
        width = self.device_obj['display']['width']
        height = self.device_obj['display']['height']
        # 先看看当前页面的输入框是否被遮挡
        count_exist = 0
        while count_exist <= 3:
            input = self.device(**settings.text_ele['one_edit_input']).exists()
            print("input-->", input)
            if input:
                break
            self.device.click(width / 2, height / 5)
            count_exist += 1
            if count_exist == 3:
                print("当前没有在直播间，请确认后再操作")
                return {"result": None, "err": "当前没有再直播间，没办法评论，请确认后再操作", "device": self.port}
        num = 0
        while num < count:
            if self.stop:
                return {"result": "已停止", "err": None}
            print("开始")
            # 点击弹出评论弹窗
            self.device(**settings.text_ele['one_edit_input']).click()

            # print("开始+++++++++++++++++++++++++++++")
            # 点击评论输入框
            self.device(**settings.text_ele['two_view_input']).click()
            # print("清空输入框+++++++++++++++++++++++++")
            # 清空输入框
            self.device.clear_text()
            # print("设置文本================================")
            # 设置输入框文本
            self.device.send_keys(input_text)
            # print("点击发送")
            # 点击发送
            self.device(**settings.text_ele['send_btn']).click()
            # 每次发送的时间间隔
            time.sleep(interval)
            num += 1
            print(f"评论第{num}次")

        return {"result": "ok", "err": None}

    @error_handle
    def click_like(self, count=1, interval=1, random_interval=None):
        """
        给主播点赞， 次数和频率可调节
        :param count:
        :param interval:
        :param random_interval:
        :return:
        """
        width = self.device_obj['display']['width']
        height = self.device_obj['display']['height']
        # 先看看当前页面的输入框是否被遮挡
        count_exist = 0
        while count_exist <= 3:
            input = self.device(**settings.text_ele['one_edit_input']).exists()
            if input:
                break
            self.device.click(width / 2, height / 5)
            count_exist += 1
            if count_exist == 3:
                print("当前没有在直播间，请确认后再操作")
                return {"result": None, "err": "当前没有再直播间，没办法点赞，请确认后再操作", "device": self.port}
        # ele = self.device(resourceId="com.ss.android.ugc.aweme:id/b5e")
        width = self.device_obj['display']['width']
        height = self.device_obj['display']['height']
        x1 = round(float(width / 7), 1)
        x2 = round(float(width / 7 * 4), 1)
        y1 = round(float(height / 4), 1)
        y2 = round(float(height / 4 * 2), 1)

        num = 0
        while num < count:
            if self.stop:
                return {"result": "已停止", "err": None}
            x = round(random.uniform(x1, x2), 1)
            y = round(random.uniform(y1, y2), 1)
            print("坐标-->>", x, y)
            self.device.double_click(x, y)
            print("random_interval", random_interval)
            if random_interval and len(random_interval) == 2:
                random_interval_time = random.uniform(float(random_interval[0]), float(random_interval[1]))
                print("随机的时间-->>", random_interval_time)
                time.sleep(random_interval_time)
                num += 1
                continue
            cur_interval = interval or 1
            time.sleep(cur_interval)
            num += 1
        return {"result": "ok", "err": None}

    @error_handle
    def loop_handle(self, func_number_list: list, param_dict: dict):
        # task_obj = {"task_number": "5", "task_param": {}}
        func_dict = {
            "5": self.set_text,
            "6": self.click_like,
            "7": self.find_given_gift
        }
        for func_number in func_number_list:
            func = func_dict.get(func_number)
            param = param_dict.get(func_number)
            res = func(**param)
            if not res.get("result"):
                print(f"步骤【{func_number}】 出错误了--->", res)
                res['device'] = self.port
                return res

        return {"result": "ok", "err": None, "device": self.port}

    @error_handle
    def run_task_queue(self, task_list, task_loop_count=1):
        """
        根据任务队列和循环次数来执行任务
        :param task_list:
        :param task_loop_count:
        :return:
        """
        cur_count = 0
        task_type_dict = {
            "5": self.set_text,
            "6": self.click_like,
            "7": self.find_given_gift
        }
        while cur_count < int(task_loop_count):
            for task_obj in task_list:
                if self.stop:
                    return {"result": "已停止", "err": None, "device": self.port}
                task_type = task_obj.get("task_type")
                params = task_obj.get("params")
                task_func = task_type_dict[task_type]
                res = task_func(**params)
                if res:
                    if not res.get("result"):
                        print(f"步骤【{task_type}】 出错误了--->", res)
                        res['device'] = self.port
                        return res

            cur_count += 1


if __name__ == '__main__':
    device = u2.connect()
    # device.debug = True
    # childs = device(resourceId="com.ss.android.ugc.aweme:id/recycler_view").child()[0]
    # for i in childs:
    #     print(i.info)
    # print("--pp-->", info)
    # print("修改输入发=============================")
    # device.set_fastinput_ime(True)
    # time.sleep(5)
    # print(device(description="小心心 1 抖币").center())
    # print(device._get_atx_agent_url())
    # device.set_fastinput_ime(True)
    # device.set_fastinput_ime(False)
    # device(resourceId="com.ss.android.ugc.aweme:id/fex").click()
    #
    # device(resourceId='com.ss.android.ugc.aweme:id/ihb').click()
    #
    # device.clear_text()
    # device.set_fastinput_ime(True)
    # device.send_keys("陈志强")
    # device(resourceId="com.ss.android.ugc.aweme:id/ih0").click()
    # device.set_fastinput_ime(False)
    # device.set_fastinput_ime(True)

    # device.send_keys("保利学府里")
    #
    # device.set_fastinput_ime(False)
    # if len(ele) > 0:
    #     ele[0].get_text()

    print("是否开启-->>", device.uiautomator.running())
    device.uiautomator.start()
    print("是否开启-->>", device.uiautomator.running())
    device_obj = device.device_info
    port = device.uiautomator.service_url.replace("http://", "").split(":")[1].split("/")[0]
    device_obj['device'] = device
    device_obj['port'] = port
    driver = Driver(device_obj)
    #driver.app_start()
    # driver.find_given_gift(gift_name="浪漫花火")
    # driver.init_gift_window()

    # {"error":null,"exitCode":0,"output":"Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.ss.android.ugc.aweme/.splash.SplashActivity }\nWarning: Activity not started, its current task has been brought to the front\n"}
    # driver.find_given_gift("娶你回家")
    # driver.app_start()
    # driver.app_stop()
    # ele = driver.device(resourceId="com.ss.android.ugc.aweme:id/g81", text="比心").click()
    # if len(ele) > 0:
    #     ele[0].double_click()
    # driver.find_room("味多美")
    # try:
    #     driver.click_like(count=5)
    #     driver.set_text(input_text="ABC", count=2)
    # except RuntimeError as e:
    #     print(e)
    #     print("链接断开了1")
    # except http.client.RemoteDisconnected as e:
    #     print(e)
    #     print("链接断开2")
    # except urllib3.exceptions.ProtocolError as e:
    #     print(e)
    #     print("链接断开3")
    # except requests.exceptions.ConnectionError as e:
    #     print(e)
    #     print("链接断开4")
    # except adbutils.errors.AdbError as e:
    #     print(e)
    #     print("链接断开5")
    # driver.open_gift_window()
